from database import engine, Base, SessionLocal
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from models import User
from fastapi import FastAPI, Depends
from routers import users, problems, homeworks, submissions, admin
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
# 新增：导入 APIRouter，确保路由正常
from fastapi import APIRouter

# 初始化 FastAPI 应用
app = FastAPI(title="智能OJ系统 API")


from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:63342"],  #
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ====================== 静态文件挂载（调整路径，避免覆盖API）======================
# 把前端静态文件挂载到 /frontend 路径，这样后端API（如 /login）不会被静态文件拦截
app.mount(
    "/frontend",
    StaticFiles(directory="frontend", html=True),
    name="frontend"
)

# 密码哈希工具
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 初始化管理员账号（启动时自动创建 admin 用户）
def init_admin():
    db: Session = SessionLocal()
    admin = db.query(User).filter(User.username == "admin").first()
    if not admin:
        hashed_password = pwd_context.hash("admin123")  # 默认密码
        new_admin = User(username="admin", password=hashed_password, role="admin")
        db.add(new_admin)
        db.commit()
    db.close()

# 启动时执行初始化
init_admin()

# ====================== 路由挂载（确保前缀与前端请求匹配）======================
# 管理员模块：路径为 /admin/xxx
app.include_router(admin.router, prefix="/admin", tags=["管理员模块"])
# 用户模块：路径为 /users/xxx（如登录接口是 /users/login）
app.include_router(users.router, prefix="/users", tags=["用户模块"])
# 题库模块：路径为 /problems/xxx
app.include_router(problems.router, prefix="/problems", tags=["题库模块"])
# 作业模块：路径为 /homeworks/xxx
app.include_router(homeworks.router, prefix="/homeworks", tags=["作业模块"])
# 提交模块：路径为 /submissions/xxx
app.include_router(submissions.router, prefix="/submissions", tags=["提交模块"])

# 根路径提示（可保留，验证后端是否启动）
@app.get("/")
def root():
    return {"message": "智能OJ系统后端运行中！"}

# 自动建表（确保数据库表结构创建）
Base.metadata.create_all(bind=engine)